<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Upload extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper(array('form', 'url', 'string'));
    }

    public function do_upload() {
        $max_size = $this->input->post('max_size');
        if ($max_size !== false) {
            if (strtoupper(substr($max_size, strlen($max_size) - 2)) == 'MB') {
                $max_size = intval($max_size) * 1024;
            } else {
                $max_size = intval($max_size);
            }
        } else {
            $max_size = 1024;
        }
        
        $allowedTypes = $this->input->post('allowed_types');
        if ($allowedTypes === false) {
            $allowedTypes = 'gif|jpg|jpeg|png';
        }
        
        $config['upload_path'] = './' . UPLOAD_DIR . '/' . date('Ym') . '/';
        $config['allowed_types'] = $allowedTypes;
        $config['max_size'] = $max_size;
        $config['encrypt_name'] = true;

        $this->load->library('upload', $config);
        
        if (!$this->upload->do_upload($this->input->post('file_element_id'))) {
            echo json_encode(array('error' => $this->upload->display_errors('', ''))) ;
        } else {
            $upload_data = $this->upload->data();
            $upload_data['encode_path'] = encode_upload_path($upload_data['full_path']);
            echo json_encode(array('error' => '', 'upload_data' => $upload_data)) ;;
        }
    }

    /**
     * 下载文件
     * @param type $filepath
     */
    public function download($doc_path) {
        echo $doc_path;
    }
}